package com.zxt.redis.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;

/**
 * @author zxt
 * spring.factories触发
 */
@Configuration
//指定初始化顺序，需要在redis自动配置初始化后
//@AutoConfigureAfter({RedisAutoConfiguration.class})
//扫描其他注解生成bean,这里是因为RedisUtil工具类bean需要初始化到
@ComponentScan({"com.zxt.redis"})
public class RedisClusterConfig {
    public RedisClusterConfig() {
    }

    /**
     * 其实这里是因为重名随便定义了一个名称
     * 解决方法1:Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
     * 解决放法2:随便改个不会重复的名字
     *
     * @param factory
     * @return
     */
    @Bean
    @ConditionalOnClass({RedisOperations.class})
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        //定义序列化
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(factory);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        template.setValueSerializer(genericJackson2JsonRedisSerializer);
        template.setHashValueSerializer(genericJackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}
